package com.tea.funct.controller;

import com.tea.common.annotation.Log;
import com.tea.common.core.controller.BaseController;
import com.tea.common.core.domain.AjaxResult;
import com.tea.common.core.page.TableDataInfo;
import com.tea.common.enums.BusinessType;
import com.tea.common.model.WxUser;
import com.tea.common.utils.StringUtils;
import com.tea.common.utils.poi.ExcelUtil;
import com.tea.funct.domain.TeaMember;
import com.tea.funct.domain.vo.InUpDetailsVo;
import com.tea.funct.service.ITeaMemberService;
import com.tea.funct.utils.util.MiniCodePosterUtil;
import com.tea.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 会员管理Controller
 *
 * @author Sophia
 * @date 2024-05-25
 */
@Slf4j
@RestController
@RequestMapping("/funct/member")
public class TeaMemberController extends BaseController {

    @Autowired
    private ITeaMemberService teaMemberService;
    @Autowired
    private MiniCodePosterUtil miniCodePosterUtil;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询会员管理列表
     */
    @PreAuthorize("@ss.hasPermi('funct:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(TeaMember teaMember) {
        startPage();
        List<TeaMember> list = teaMemberService.selectTeaMemberList(teaMember);
        if (list != null && list.size() > 0) {
            for (TeaMember member : list) {
                WxUser wxUser = sysUserService.selectWxUserByUserId(member.getUserId());
                if (wxUser != null) {
                    member.setMemberPhone(wxUser.getPhoneNumber());
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询所有用户信息
     */
    @PreAuthorize("@ss.hasPermi('funct:member:list')")
    @GetMapping("/listAllWxUser")
    public TableDataInfo listAllWxUser() {
        List<WxUser> list = teaMemberService.selectAllWxUserList();
        return getDataTable(list);
    }


    /**
     * 导出会员管理列表
     */
    @PreAuthorize("@ss.hasPermi('funct:member:export')")
    @Log(title = "会员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TeaMember teaMember) {
        List<TeaMember> list = teaMemberService.selectTeaMemberList(teaMember);
        ExcelUtil<TeaMember> util = new ExcelUtil<TeaMember>(TeaMember.class);
        util.exportExcel(response, list, "会员管理数据");
    }

    /**
     * 获取会员管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('funct:member:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(teaMemberService.selectTeaMemberById(id));
    }

    /**
     * 新增会员管理
     */
    @PreAuthorize("@ss.hasPermi('funct:member:add')")
    @Log(title = "会员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TeaMember teaMember) {
        return toAjax(teaMemberService.insertTeaMember(teaMember));
    }

    /**
     * 修改会员管理
     */
    @PreAuthorize("@ss.hasPermi('funct:member:edit')")
    @Log(title = "会员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TeaMember teaMember) {
        return toAjax(teaMemberService.updateTeaMember(teaMember));
    }

    /**
     * 删除会员管理
     */
    @PreAuthorize("@ss.hasPermi('funct:member:remove')")
    @Log(title = "会员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(teaMemberService.deleteTeaMemberByIds(ids));
    }

    /**
     * 批量重新生成小程序码和推广海报
     *
     * @param vo
     * @return
     */
    @PostMapping("/anewCreateAllCode")
    public AjaxResult createMiniCodeAndPoster(@RequestBody InUpDetailsVo vo) {
        log.info("重新生成小程序码和推广海报入参：{}", vo);
        try {
            List<Long> ids = vo.getIds();
            if (Objects.isNull(ids)) {
                log.info("重新生成小程序码及推广海报入参不全");
                return AjaxResult.error("ids不能为空！");
            }
            String createFlag = vo.getCreateFlag();
            if (StringUtils.isBlank(createFlag)) {
                log.info("生成标识为空，则默认都重新生成！");
                createFlag = "0"; // 0:小程序码及推广海报；1:小程序码; 2:推广海报
            }
            for (Long id : ids) {
                TeaMember teaMember = teaMemberService.selectTeaMemberById(id);
                if (StringUtils.equals(createFlag, "0")) {
                    // 都需要重新生成
                    String qrCodeFileName = miniCodePosterUtil.createMiniQrCodeByReferralCode(teaMember.getReferralCode());
                    teaMember.setSmallShareQrcode(qrCodeFileName);
                    String pushPosterImage = miniCodePosterUtil.createPushPoster(qrCodeFileName, teaMember.getReferralCode());
                    teaMember.setRecommendedPoster(pushPosterImage);
                } else if (StringUtils.equals(createFlag, "1")) {
                    // 只生成小程序二维码
                    String qrCodeFileName = miniCodePosterUtil.createMiniQrCodeByReferralCode(teaMember.getReferralCode());
                    teaMember.setSmallShareQrcode(qrCodeFileName);
                } else if (StringUtils.equals(createFlag, "2")) {
                    // 只生成推广海报
                    String pushPosterImage = miniCodePosterUtil.createPushPoster(teaMember.getSmallShareQrcode(), teaMember.getReferralCode());
                    teaMember.setRecommendedPoster(pushPosterImage);
                }
                teaMemberService.updateTeaMember(teaMember);
            }
        } catch (Exception e) {
            log.error("重新批量生成会员二维码及海报出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 重新生成小程序码和推广海报
     *
     * @param id
     * @param createFlag
     * @return
     */
    @GetMapping("/anewCreateCode/{id}/{createFlag}")
    public AjaxResult createMiniCodeAndPoster(@PathVariable("id") Long id, @PathVariable("createFlag") String createFlag) {
        log.info("重新生成小程序码和推广海报入参：id:{}, flag:{}", id, createFlag);
        try {
            TeaMember teaMember = teaMemberService.selectTeaMemberById(id);
            if (StringUtils.equals(createFlag, "0")) {
                // 都需要重新生成
                String qrCodeFileName = miniCodePosterUtil.createMiniQrCodeByReferralCode(teaMember.getReferralCode());
                teaMember.setSmallShareQrcode(qrCodeFileName);
                String pushPosterImage = miniCodePosterUtil.createPushPoster(qrCodeFileName, teaMember.getReferralCode());
                teaMember.setRecommendedPoster(pushPosterImage);
            } else if (StringUtils.equals(createFlag, "1")) {
                // 只生成小程序二维码
                String qrCodeFileName = miniCodePosterUtil.createMiniQrCodeByReferralCode(teaMember.getReferralCode());
                teaMember.setSmallShareQrcode(qrCodeFileName);
            } else if (StringUtils.equals(createFlag, "2")) {
                // 只生成推广海报
                String pushPosterImage = miniCodePosterUtil.createPushPoster(teaMember.getSmallShareQrcode(), teaMember.getReferralCode());
                teaMember.setRecommendedPoster(pushPosterImage);
            }
            int success = teaMemberService.updateTeaMember(teaMember);
        } catch (Exception e) {
            log.error("重新生成会员二维码及海报出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

}
